import 'package:flutter/material.dart';
import 'package:jingyuan/commmon/Utils.dart';

class Opencc {
  static Map<String, List<String>> _t2s = {};
  static Map<String, List<String>> _s2t = {};
  static init() async {
    await _load(_t2s, 'assets/opencc/TSCharacters.txt');
    await _load(_s2t, 'assets/opencc/STCharacters.txt');
  }

  static _load(Map<String, List<String>> retMap, String path) async {
    final str = await Utils.readAssetsStringFile(path);
    var lines = str.split('\n') as List<String>;
    for (var element in lines) {
      var words = element.split('\t');
      if (words.length == 2) {
        retMap[words[0]] = words[1].split(' ');
      }
    }
  }

  static t2s(String str, bool isReg) {
    return _convert(_t2s, str, isReg);
  }

  static s2t(String str, bool isReg) {
    return _convert(_s2t, str, isReg);
  }

  static _convert(Map<String, List<String>> whichMap, String from, bool isReg) {
    String r = "";
    from.characters.forEach((element) {
      var to = whichMap[element];
      if (to == null) {
        r += element;
      } else {
        if (r.length == 1) {
          r += to[0];
        } else {
          if (isReg) {
            r += "(${to.join('|')})";
          } else {
            r += to[0];
          }
        }
      }
    });
    return r;
  }
}
